package com.apes.scm.masterdata.party.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.ChangeCompany;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.repository.ChangeCompanyRepository;
import com.apes.scm.masterdata.party.repository.PartyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("changeCompanyService")
public class ChangeCompanyService extends DomainService {

    @Autowired
    private ChangeCompanyRepository changeCompanyRepository;

    @Autowired
    private PartyRepository partyRepository;

    /**
     * 修改公司名称创建
     * @param request
     * @return
     */
    public ChangeCompany create(SimpleRequest request){
        ChangeCompany changeCompany =request.getO(ChangeCompany.class);
        changeCompany.setState("sent");
        changeCompany.setCreateDate(new Date());
        changeCompany.setOriginalCompanyId((Long) changeCompany.getOriginalCompany().getParty().getId());
        changeCompany.setOriginalCompanyName(changeCompany.getOriginalCompany().getName());

        changeCompany=changeCompanyRepository.saveAndFlush(changeCompany);
        return changeCompany;
    }

    /**
     * 修改公司名称修改
     * @param request
     * @return
     */
    public ChangeCompany update(SimpleRequest request){
        ChangeCompany changeCompany =request.getO(ChangeCompany.class);
        changeCompany.setState("sent");
        changeCompany.setCreateDate(new Date());

        changeCompany=changeCompanyRepository.saveAndFlush(changeCompany);
        return changeCompany;
    }

    /**
     * 修改公司名称修改
     * @param request
     * @return
     */
    public String delete(SimpleRequest request){
        ChangeCompany changeCompany =request.getO(ChangeCompany.class);
        changeCompany.setState("delete");
        changeCompany.setDeleteDate(new Date());
        changeCompany.setDeleteUID(this.getPerson(request));

        changeCompanyRepository.saveAndFlush(changeCompany);
        return "删除成功";
    }

    /**
     * 修改公司名称修改
     * @param request
     * @return
     */
    public ChangeCompany approve(SimpleRequest request){
        ChangeCompany changeCompany = request.getO(ChangeCompany.class);
        changeCompany.setState("approve");
        changeCompany.setApproveDate(new Date());
        changeCompany.setApproveId(this.getPerson(request));

        //修改
        Party party = partyRepository.findOne(changeCompany.getOriginalCompany().getParty().getId());
        party.setName(changeCompany.getNewCompany());
        partyRepository.saveAndFlush(party);

        changeCompany = changeCompanyRepository.saveAndFlush(changeCompany);
        return changeCompany;
    }

}
